﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace FySystem.Net.IOT.RemoteControl
{
    public class RemoteControlSender
    {
        /// <summary>
        /// 向远端发送远控指令
        /// </summary>
        /// <param name="remoteIp"></param>
        /// <param name="port"></param>
        /// <param name="remoteCommand"></param>
        /// <returns></returns>
        public RemoteResult SendCommand(string remoteIp, int port, RemoteCommand remoteCommand)
        {
            RemoteResult res = null;
            Socket socket = null;
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(remoteIp), port);
                socket.SendTimeout = 15000;
                socket.ReceiveTimeout = 15000;

                string jsn = JsonSerializer.Serialize(remoteCommand, new JsonSerializerOptions()
                {
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
                byte[] b = Encoding.UTF8.GetBytes(jsn);

                socket.Connect(endPoint);
                socket.Send(b);

                //接收数据
                byte[] buffer = new byte[4096];         //缓存大一点，防止一次接收不完，反正服务器内存多
                int reads = socket.Receive(buffer);
                if (reads > 0)
                {
                    jsn = Encoding.UTF8.GetString(buffer, 0, reads);
                    res = JsonSerializer.Deserialize<RemoteResult>(jsn, new JsonSerializerOptions()
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    });
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (socket != null)
                {
                    try
                    {
                        socket.Dispose();
                    }
                    catch { }
                }
            }
            return res;
        }
    }
}
